package com.example.guiguiapplicatio.fragment.examination;

import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TabHost;

import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.guiguiapplicatio.api.GetExaminationRecordApi;
import com.example.guiguiapplicatio.api.Interface.GetExaminationRecordCallback;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.Response.ExaminationRecord;
import com.example.guiguiapplicatio.databinding.FragmentExaminationRecordBinding;
import com.example.guiguiapplicatio.fragment.examination.adapter.ExaminationRecordAdapter;
import com.example.guiguiapplicatio.fragment.examination.placeholder.ExaminationRecordPlaceholderContent;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ExaminationRecordFragment extends Fragment implements GetExaminationRecordCallback {
    FragmentExaminationRecordBinding binding;
    ExaminationRecordAdapter adapter;
    private GetExaminationRecordApi getExaminationRecordApi;
    private TabHost tabHost;
    private int SHOW_SIFT = 0;
    private ArrayList<String> tmpSelectedId1 = new ArrayList<String>();
    private Map<String, Boolean> tmpSelectedId3;
    private CheckBox[] checkBoxes;
    private ArrayList<String> searthList = new ArrayList<String>();
    private String idname = "-1";
    private Integer starttime = -1;
    private ArrayList<String> listenerNames = new ArrayList<>();


    public static List<ExaminationRecordPlaceholderContent.PlaceholderItem> NOW_ITEMS = new ArrayList<ExaminationRecordPlaceholderContent.PlaceholderItem>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentExaminationRecordBinding.inflate(inflater, container, false);
        View view = binding.getRoot();
        binding.examinationList.setLayoutManager(new LinearLayoutManager(binding.getRoot().getContext()));
        NOW_ITEMS = ExaminationRecordPlaceholderContent.ITEMS;
        adapter = new ExaminationRecordAdapter(NOW_ITEMS, getContext());
        binding.examinationList.setAdapter(adapter);

        getExaminationRecordApi = new GetExaminationRecordApi(this);
        getExaminationRecordApi.setGetExaminationRecordCallback(this);


//       初始化复选框
        checkBoxes = new CheckBox[]{
                view.findViewById(R.id.gaoxueya),
                view.findViewById(R.id.gaoxuetang),
                view.findViewById(R.id.gaoxuezhi),
                view.findViewById(R.id.ertong),
                view.findViewById(R.id.laoren)
        };
        tmpSelectedId3 = new HashMap<>();
        // 初始化复选框状态的 Map，所有复选框默认为未选中状态
        for (CheckBox checkBox : checkBoxes) {
            String text = checkBox.getText().toString();
            tmpSelectedId3.put(text, false);
        }
        Log.d("info", "列表:" + idname + "列表:" + starttime + "列表:" + listenerNames.toString());
        getExaminationRecordApi.performGetExaminationRecord("-1", -1, listenerNames);
        siftTrains();

        binding.searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                idname = binding.etSearchtext.getText().toString();
                if (idname.isEmpty()) {
                    idname = "-1";
                }
                getExaminationRecordApi.performGetExaminationRecord(idname, -1, listenerNames);
                Log.d("info", idname);

            }
        });
        binding.servicBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });
        binding.examinationFab.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_examinationRecordFragment_to_examinationStartFragment));
        return view;
    }

    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        super.onResume();
    }

    private void siftTrains() {
        binding.tabhost.setVisibility(View.INVISIBLE);
        tabHost = binding.tabhost;
        tabHost.setup();
        TabHost.TabSpec myTab1 = tabHost.newTabSpec("体检时间");
        myTab1.setIndicator("体检时间");
        myTab1.setContent(R.id.examination_time_group);
        tabHost.addTab(myTab1);

        TabHost.TabSpec myTab2 = tabHost.newTabSpec("所属人群");
        myTab2.setIndicator("所属人群");
        myTab2.setContent(R.id.scroll_view);
        tabHost.addTab(myTab2);
        binding.imgBtnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SHOW_SIFT == 0) {
                    SHOW_SIFT = 1;
                    binding.tabhost.setVisibility(View.VISIBLE);
                } else {
                    SHOW_SIFT = 0;
                    binding.tabhost.setVisibility(View.INVISIBLE);
                }

            }
        });
        binding.examinationTimeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = group.findViewById(checkedId);
                if (radioButton != null) {
                    String examinationTime = radioButton.getText().toString();

                    if (examinationTime.equals("最近三个月")) {
                        starttime = 0;
                    } else if (examinationTime.equals("最近半年")) {
                        starttime = 1;
                    } else if (examinationTime.equals("最近一年")) {
                        starttime = 2;
                    } else if (examinationTime.equals("全部时间")) {
                        starttime = -1;
                    }
                } else {
                    starttime = -1;
                }
                siftAndRemake();
            }
        });
        CompoundButton.OnCheckedChangeListener checkBoxListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String text = buttonView.getText().toString();
                tmpSelectedId3.put(text, isChecked);
                siftAndRemake();
            }

        };
        for (CheckBox checkBox : checkBoxes) {
            checkBox.setOnCheckedChangeListener(checkBoxListener);
        }
    }

    private void siftAndRemake() {
        binding.searchSift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (Map.Entry<String, Boolean> entry : tmpSelectedId3.entrySet()) {
                    if (entry.getValue()) { // 只添加选中的复选框文本
                        listenerNames.add(entry.getKey());
                    }
                }
                Log.d("info", "体检开始时间为：" + starttime.toString());
                Log.d("info", "体检人群类型为：" + listenerNames.toString());
                getExaminationRecordApi.performGetExaminationRecord("-1", starttime, listenerNames);
                SHOW_SIFT = 0;
                binding.tabhost.setVisibility(View.INVISIBLE);
                searchClear();

            }
        });
        binding.searchRemake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchClear();
                getExaminationRecordApi.performGetExaminationRecord("-1", -1, listenerNames);
            }
        });
    }

    private void searchClear() {
        tmpSelectedId3.clear();
        listenerNames.clear();
        starttime = -1;
        binding.examinationTimeGroup.clearCheck();
        binding.gaoxueya.setChecked(false);
        binding.gaoxuetang.setChecked(false);
        binding.gaoxuezhi.setChecked(false);
        binding.ertong.setChecked(false);
        binding.laoren.setChecked(false);
    }

    @Override
    public void onERSuccess(ResponseBody<List<ExaminationRecord>> responseBody) {
        Object data = responseBody.getData();
        if (data instanceof List) {
            List<ExaminationRecord> examinationRecords = (List<ExaminationRecord>) data;
            Log.d("info", "响应的签约记录数据：" + examinationRecords.toString());
            NOW_ITEMS.clear();
            for (ExaminationRecord examinationRecord : examinationRecords) {
                ExaminationRecordPlaceholderContent.addItem(new ExaminationRecordPlaceholderContent.PlaceholderItem(
                        examinationRecord.getExaminationid(),
                        examinationRecord.getIdcard(),
                        examinationRecord.getName(),
                        examinationRecord.getSex(),
                        examinationRecord.getAge(),
                        examinationRecord.getStarttime(),
                        examinationRecord.getListenername()
                ));
            }
            adapter.notifyDataSetChanged();
        }
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "体检记录列表响应成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onERFailure(String errorMessage) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "体检记录列表响应失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
}